package edu.missouri.mapandcompass;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;
//import com.maps.GMItemizedOverlay;
//import com.maps.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MapCompass extends Activity {
	
	int NUM_VALUES = 100;
	int NUM_AVERAGES = 100;
	float running_array[] = new float[NUM_VALUES];
	int i = 0;
	float sum = 0;
	float sum2 = 0;
	float average = 0;
	float average2 = 0;
	
	TextView tv1;
	TextView tv2;
	TextView tv3;
	Button button;
	
	private static SensorManager mySensorManager;
	
	private LocationManager myLocationManager = null;
    LocationListener locationListener;
    
    int latitude = 0;
    int longitude = 0;
	
	float[] dAcc = new float[3];
	float[] dMag = new float[3];
	float[] cBAcc=new float[3];
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button = (Button)findViewById(R.id.button);
        button.setText("Go");
        tv1 = (TextView)findViewById(R.id.tv1);
        tv2 = (TextView)findViewById(R.id.tv2);
        tv3 = (TextView)findViewById(R.id.tv3);
        mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        
        myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        locationListener = new LocationListener() {  
			public void onLocationChanged(Location location) {   
				// log it when the location changes  
				if (location != null) {  
					Log.i("SuperMap", "Location changed : Lat: "  
							+ location.getLatitude() + " Lng: "  
							+ location.getLongitude());  
					ShowMyOwnGPSPosition();
					//ShowGroupsOverlay();
				}  
			}  
        
			public void onProviderDisabled(String provider) {  
            
			}  
        
			public void onProviderEnabled(String provider) {  
           
			}  
        
			public void onStatusChanged(String provider, int status, Bundle extras) {  
           
			}  
		};  
		myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,  
				1000, 0, locationListener);
		
		button.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				sum2 = 0;
				for(int j = 0; j < 3 * NUM_AVERAGES; j++){
					if(j % 3 == 0){
						sum2 = sum2 + average;
					}
						
				}
				average2 = sum2/NUM_AVERAGES;
				tv3.setText(average2 + "\n" + latitude + " " + longitude);
				
			}
			
		});
    }
    
    private void updateOrientation(float[] values) {
		
			if(values[0] < 0)
				running_array[i] = values[0] + 360;
			else
				running_array[i] = values[0];
			i++;
			sum = 0;
			if(i >= NUM_VALUES)
				i = 0;
			for(int j = 0; j < running_array.length; j++){
				sum = sum + running_array[j];
			}
			average = 0;
			for(int j = 0; j < running_array.length; j++){
				average = average + (float)((sum * Math.sin(running_array[j])) / (sum  * Math.cos(running_array[j])));
			}
			average = (float)Math.atan(average);
			tv1.setText(Float.toString(average));
    }
    
    private float[] calculateOrientation() {
		float[] values = new float[3];
		float[] R = new float[9];
		float[] outR = new float[9];

		SensorManager.getRotationMatrix(R, null, dAcc, dMag);
		SensorManager.remapCoordinateSystem(R, 
				SensorManager.AXIS_X, 
				SensorManager.AXIS_Z, 
				outR);

		SensorManager.getOrientation(outR, values);
		//SensorManager.getOrientation(R, values);

		// Convert from Radians to Degrees.
		values[0] = (float) Math.toDegrees(values[0]);
		values[1] = (float) Math.toDegrees(values[1]);
		values[2] = (float) Math.toDegrees(values[2]);




		return values;
	}
    
    private final SensorEventListener mySensorEventListener = new SensorEventListener() {
		public void onSensorChanged(SensorEvent event) {

			int etype = event.sensor.getType();


			//Record the value and time
			switch (etype) {
			case Sensor.TYPE_ACCELEROMETER:
				dAcc[0]=event.values[0]-cBAcc[0];
				dAcc[1]=event.values[1]-cBAcc[1];
				dAcc[2]=event.values[2]-cBAcc[2];
				//        		if (ptAcc!=0) dt=(etime-ptAcc)/N2S;
				//        		ptAcc=etime;
				break;
			case Sensor.TYPE_MAGNETIC_FIELD:
				dMag[0]=event.values[0];
				dMag[1]=event.values[1];
				dMag[2]=event.values[2];
				//        		if (ptMag!=0) dt=(etime-ptMag)/N2S;
				//        		ptMag=etime;

				break;
			}


			updateOrientation(calculateOrientation());
		}
		public void onAccuracyChanged(Sensor sensor, int accuracy) {}
    };
    
    @Override
	protected void onResume() {
		super.onResume();


		//Sensors
		Sensor sOri = mySensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
		Sensor sAcc = mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		Sensor sMag = mySensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

		int rate=SensorManager.SENSOR_DELAY_FASTEST;

		mySensorManager.registerListener(mySensorEventListener, sOri, rate);
		mySensorManager.registerListener(mySensorEventListener, sAcc, rate);
		if (sMag!=null) mySensorManager.registerListener(mySensorEventListener, sMag, rate);

	}

	@Override
	protected void onStop() {
		mySensorManager.unregisterListener(mySensorEventListener);
		super.onStop();
	}
    
    private void ShowMyOwnGPSPosition(){
		Location location = myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
		if(location != null){
			latitude =  (int) ((int)(location.getLatitude()*1e6));     
			longitude = (int) ((int)(location.getLongitude()*1e6));
			tv2.setText(latitude + " " + longitude);
		}
	}

}